import turbogears   as tg

import logging
import cherrypy
import sqlobject
from sqlalchemy.exceptions import SQLError
import kaizen.controllers
from kaizen.model import Context,session
from turbogears import identity, expose, validate, validators, redirect, error_handler, flash, view
from formencode import validators

log = logging.getLogger("kaizen.subcontrollers.context")

class ContextController:

    @expose(template="kaizen.templates.viewContext", content_type='text/html; charset=utf-8')
    @validate(validators={"title" : validators.NotEmpty()})
    @error_handler()
    def update(self, title, id, tg_errors=None, **keywords):
        log.debug("updateContext")
        if tg_errors:
            log.debug("no title")
            tg.flash("You must enter a title")
            return dict()
        try:
          log.debug("update context")
          context = session.get(Context,id)
          context.title=title
          context.flush()
        except SQLError:
           tg.flash("Context with such title already exists")
           return dict(context=context)
        tg.flash("Context updated")
        kaizen.controllers.context_provider.update()
        return dict(context=context)

    @expose(template="kaizen.templates.welcome", content_type='text/html; charset=utf-8')
    @validate(validators={"title" : validators.NotEmpty()})
    @error_handler()
    def create(self, title, tg_errors=None, **keywords):
        log.debug("create context")
        if tg_errors:
            log.debug("no title")
            tg.flash("You must enter a title")
            return dict(tg_template="kaizen.templates.createContext")
        try:
          log.debug("new context")
          context = Context(title=title)
          context.flush()
        except SQLError,x:
           log.error("error",x)
           tg.flash("Context already exists")
           return dict()
        tg.flash("Context added")
        kaizen.controllers.context_provider.update()
        return dict()

    @expose(template="kaizen.templates.welcome", content_type='text/html; charset=utf-8')
    @validate(validators={"title" : validators.NotEmpty()})
    @error_handler()
    def delete(self, id, tg_errors=None, **keywords):
        context = session.get(Context, id)
        context.delete()
        context.flush()
        tg.flash("Context deleted")
        kaizen.controllers.context_provider.update()
        return dict()

    @expose(template="kaizen.templates.viewContext", content_type='text/html; charset=utf-8')
    @error_handler()
    def view(self, id, tg_errors=None, **keywords):
          log.debug("new context")
          context = session.get(Context,id)
          return dict(context=context, previousPage="kaizen.templates.viewContext")
